package com.lock.reentrantLock;

import java.util.Random;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @PackageName:com.lock.reentrantLock
 * @ClassName:Test02
 * @Description: lock锁同步不同方法中的同步代码块（使用同一个锁对象）
 * @Author: zhangxiaoyu
 * @date 2021/1/19 16:06
 */
public class Test02 {

    //定义一个锁对象
    static Lock lock = new ReentrantLock();

    public static void sm1() {

        //经常在try代码块中lock锁获得后，经常在finally中释放锁
        try {
            //获得锁
            lock.lock();
            System.out.println(Thread.currentThread().getName() + "--- method 1 -- " + System.currentTimeMillis());
            Thread.sleep(new Random().nextInt(1000));
            System.out.println(Thread.currentThread().getName() + "--- method 1 -- " + System.currentTimeMillis());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            //释放锁
            lock.unlock();
        }
    }

    public static void sm2() {

        //经常在try代码块中lock锁获得后，经常在finally中释放锁
        try {
            //获得锁
            lock.lock();
            System.out.println(Thread.currentThread().getName() + "--- method 2 -- " + System.currentTimeMillis());
            Thread.sleep(new Random().nextInt(1000));
            System.out.println(Thread.currentThread().getName() + "--- method 2 -- " + System.currentTimeMillis());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            //释放锁
            lock.unlock();
        }
    }

    public static void main(String[] args) {
        Runnable r1 = new Runnable() {
            @Override
            public void run() {
                sm1();
            }
        };


        Runnable r2 = new Runnable() {
            @Override
            public void run() {
                sm2();
            }
        };

        new Thread(r1).start();
        new Thread(r1).start();
        new Thread(r1).start();

        new Thread(r2).start();
        new Thread(r2).start();
        new Thread(r2).start();

    }

}
